package middleware

import (
	"fmt"
	"gin_blog/model"
	_ "gin_blog/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func RequestInfos() gin.HandlerFunc {
	return func(context *gin.Context) {
		path := context.FullPath()
		method := context.Request.Method
		fmt.Println("请求路径：" + path)
		fmt.Println("请求方式：" + method)
	}
}

func RequestAuth() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//token := context.Param("token")
		//token := ctx.Query("token")
		token := ctx.Request.Header.Get("token")
		fmt.Println("middleware中token:", token)
		var userTokenModel model.UserTokenModel
		db := model.GetDB()
		db.First(&userTokenModel, "token=?", token)
		fmt.Println("userTokenModel.Token:", userTokenModel.Token)
		fmt.Println("userTokenModel.UserId:", userTokenModel.UserId)
		if userTokenModel.UserId == 0 {
			ctx.JSON(http.StatusForbidden, map[string]interface{}{
				"code": 4104,
				"msg":  "非法用户",
				"data": "",
			})
			//中间件中直接退出用ctx.Abort()
			ctx.Abort()
		} else {
			fmt.Println("正常用户")
		}

	}
}

type Options struct {
	Origin string
}

func CORS(options Options) gin.HandlerFunc {
	return func(c *gin.Context) {
		if options.Origin != "" {
			c.Writer.Header().Set("Access-Control-Allow-Origin", options.Origin)
		}
		c.Writer.Header().Set("Access-Control-Max-Age", "86400")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "*")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		c.Writer.Header().Set("Access-Control-Expose-Headers", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		} else {
			c.Next()
		}
	}
}

func Requestpermssion() gin.HandlerFunc {
	return func(context *gin.Context) {
		path := context.FullPath()
		method := context.Request.Method
		fmt.Println("请求路径：" + path)
		fmt.Println("请求方式：" + method)
	}
}
